package com.xyz.ai.controller;

import com.xyz.ai.assistant.ChatAgent;
import com.xyz.ai.bean.ChatForm;
import com.xyz.ai.service.impl.SseService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@RestController
@Tag(name="小程")
@CrossOrigin(origins = "*")
@RequestMapping("/ai")
@Slf4j
public class EduChatController {


    @Autowired
    private ChatAgent chatAgent;

    @Autowired
    private SseService sseService;




    private final List<SseEmitter> emitters = new CopyOnWriteArrayList<>();
    @GetMapping(value = "/stream/{sessionId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter stream(@PathVariable String sessionId) {
        log.info("stream sessionId:{}",sessionId);
        return sseService.createEmitter(sessionId);
    }

/**
 * Post mapping to clear chat history for a specific session
 *
 * @param sessionId The unique identifier of the session whose history needs to be cleared
 */
    @PostMapping("/clear/{sessionId}")
    public void clearHistory(@PathVariable String sessionId) {
        // 这里可以添加清除历史记录的逻辑
        sseService.sendToClient(sessionId, "system", "对话历史已清除", "system");
    }

    @PostMapping("/send")
    public void sendMessage(
            @RequestParam String sessionId,
            @RequestParam String message,
            @RequestParam(defaultValue = "user") String username) {
        log.info("sendMessage sessionId:{},message:{},username:{}",sessionId,message,username);
        sseService.sendMessage(sessionId, message, username);
        log.info("send sendMessage sessionId:{}",sessionId);
    }

//    @Operation(summary = "对话")
//    @PostMapping(value = "/chat",produces = "text/stream;charset=utf-8")
//    public Flux<String> chat(@RequestBody ChatForm chatForm) {
//        return xiaozhiAgent.chat(chatForm.getMemoryId(), chatForm.getMessage())
//                .map(response -> new String(response.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
//    }
//
//    @Operation(summary = "对话")
//    @PostMapping(value = "/chat",produces = "text/stream;charset=utf-8")
//    public Flux<String> chat(@RequestBody ChatForm chatForm) {
//        return chatAgent.chat( chatForm.getMessage())
//                .map(response -> new String(response.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
//    }

    @Operation(summary = "对话")
    @PostMapping(value = "/chat",produces = "text/stream;charset=utf-8")
    public Flux<String> chat(@RequestBody ChatForm chatForm) {
        // 打印请求日志
        System.out.println("请求参数: " + chatForm.getMessage());
        log.info("请求参数: " + chatForm.getMessage());

        return chatAgent.chat(chatForm.getMessage())
                .map(response -> {
                    // 打印响应日志
                    String result = new String(response.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
                    log.info("响应内容: " + result);
                    return result;
                });
    }
    // 发送消息
    @PostMapping("/sse/send")
    public void sendMessage(@RequestBody ChatForm chatForm) {
        List<SseEmitter> deadEmitters = new ArrayList<>();

        emitters.forEach(emitter -> {
            try {
                emitter.send(SseEmitter.event()
                        .name("MESSAGE")
                        .data(chatForm));
            } catch (IOException e) {
                deadEmitters.add(emitter);
            }
        });

        emitters.removeAll(deadEmitters);
    }

}
